package com.leanin.form.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leanin.form.exception.ExceptionCast;
import com.leanin.form.mapper.LeaninFollowFormDeptMapper;
import com.leanin.form.mapper.LeaninSatisfyFormDeptMapper;
import com.leanin.form.mapper.LeaninSatisfyFormMapper;
import com.leanin.form.model.LeaninFollowForm;
import com.leanin.form.model.LeaninSatisfyForm;
import com.leanin.form.model.LeaninSatisfyFormDept;
import com.leanin.form.model.request.FormQueryDTO;
import com.leanin.form.model.request.SatisfyFormDTO;
import com.leanin.form.model.response.*;
import com.leanin.form.model.response.satisfyform.SatisfyFormCode;
import com.leanin.form.service.SatisfyFormService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author CPJ.
 * @date 2019/6/17.
 * @time 9:59.
 */
@Service
public class SatisfyFormServiceImpl implements SatisfyFormService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SatisfyFormServiceImpl.class);

    @Autowired
    private LeaninSatisfyFormMapper leaninSatisfyFormMapper;

    @Autowired
    private LeaninSatisfyFormDeptMapper leaninSatisfyFormDeptMapper;

    private Integer getDownLoadCount(){
        Random random = new Random();
        int count = random.nextInt(50);
        return count + 50 ;
    }


    //判断参数是否合理
    private void checkParam(SatisfyFormDTO satisfyFormDTO) {
        if (satisfyFormDTO.getFormName() == null) {//表单名为空
            ExceptionCast.cast(SatisfyFormCode.FORM_NAME_NULL);
        }
        if (satisfyFormDTO.getFormName().length() > 50){//表单名称  超过 50 字
            ExceptionCast.cast(SatisfyFormCode.FORM_NAME_LENGTH_ERROR);
        }
        if (satisfyFormDTO.getFormTitle().length() > 150){//表单头  超过 150 字
            ExceptionCast.cast(SatisfyFormCode.FORM_TITLE_LENGTH_ERROR);
        }
        if (satisfyFormDTO.getFormEnd().length() > 150){//表单名称  超过 150 字
            ExceptionCast.cast(SatisfyFormCode.FORM_END_LENGTH_ERROR);
        }
        if (satisfyFormDTO.getFormContent() == null) {//表单内容为空
            ExceptionCast.cast(SatisfyFormCode.FORM_CONTENT_NULL);
        }



    }

    //添加表单和科室的关联表
    private void  InsertDept(SatisfyFormDTO satisfyFormDTO){
        //添加宣教表单关联科室
        List<String> depts = satisfyFormDTO.getDepts();
        if (depts != null && depts.size() > 0) {//判断宣教科室是否为空
            List<LeaninSatisfyFormDept> params = new ArrayList<>();
            for (String dept : depts) {
                LeaninSatisfyFormDept leaninEduFormDept = new LeaninSatisfyFormDept();
                leaninEduFormDept.setSatisfyFormId(satisfyFormDTO.getId());
                leaninEduFormDept.setDeptCode(dept);
                params.add(leaninEduFormDept);
            }
            leaninSatisfyFormDeptMapper.insertList(params);
        }
    }

    @Override
    @Transactional
    public ResponseResult addSatisfyForm(SatisfyFormDTO satisfyFormDTO) {
        LOGGER.info("添加的满意度表单信息:{}", JSON.toJSONString(satisfyFormDTO));
        //检测参数是否合理
        checkParam(satisfyFormDTO);
        List<LeaninSatisfyForm> leaninSatisfyForms = leaninSatisfyFormMapper.selectByFormName(satisfyFormDTO.getFormName());
        if (leaninSatisfyForms.size() > 0) {//宣教表单名重复
            ExceptionCast.cast(SatisfyFormCode.FORM_NAME_REPETITION);
        }
        LeaninSatisfyForm leaninSatisfyForm = new LeaninSatisfyForm();
        satisfyFormDTO.setFormCreateTime(new Date());
        satisfyFormDTO.setDownloadCount(getDownLoadCount());
        BeanUtils.copyProperties(satisfyFormDTO,leaninSatisfyForm);
        leaninSatisfyFormMapper.insertSelective(leaninSatisfyForm);
        satisfyFormDTO.setId(leaninSatisfyForm.getId());
        //满意度表单相关科室添加
        InsertDept(satisfyFormDTO);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    @Override
    @Transactional
    public ResponseResult updateSatisfyForm(SatisfyFormDTO satisfyFormDTO) {
        LOGGER.info("修改的满意度表单信息:{}",JSON.toJSONString(satisfyFormDTO));
        //检测参数是否合理
        checkParam(satisfyFormDTO);
        List<LeaninSatisfyForm> leaninSatisfyForms = leaninSatisfyFormMapper.selectByFormName(satisfyFormDTO.getFormName());
        if (leaninSatisfyForms.size() > 1) {//宣教表单名重复
            ExceptionCast.cast(SatisfyFormCode.FORM_NAME_REPETITION);
        }
        if (satisfyFormDTO.getId() == null){//传递id 为空
            ExceptionCast.cast(SatisfyFormCode.FORM_NOT_EXIST);
        }
        LeaninSatisfyForm leaninSatisfyForm = leaninSatisfyFormMapper.selectByPrimaryKey(satisfyFormDTO.getId());
        if (leaninSatisfyForm == null){
            ExceptionCast.cast(SatisfyFormCode.FORM_NOT_EXIST);
        }
        LeaninSatisfyForm satisfyForm = new LeaninSatisfyForm();
        BeanUtils.copyProperties(satisfyFormDTO,satisfyForm);
        satisfyForm.setFormCreateTime(leaninSatisfyForm.getFormCreateTime());
        satisfyForm.setDownloadCount(leaninSatisfyForm.getDownloadCount());
        //修改表单信息
        leaninSatisfyFormMapper.updateByPrimaryKeySelective(satisfyForm);
        //修改表单关联科室
        leaninSatisfyFormDeptMapper.deleteByFormId(satisfyFormDTO.getId());
        InsertDept(satisfyFormDTO);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    @Override
    public QueryResponseResult findByParam(FormQueryDTO formQueryDTO) {
        Integer page = formQueryDTO.getPage();
        if (page == null || page < 1){
            page = 1;
        }
        Integer pageSize = formQueryDTO.getPageSize();
        if (pageSize == null || pageSize < 0){
            pageSize = 10;
        }
        PageHelper.startPage(page,pageSize);
        Page<SatisfyFormVO> satisfyFormVOS = (Page<SatisfyFormVO>) leaninSatisfyFormMapper.findByParam(formQueryDTO);
        //封装返回参数
        QueryResult<SatisfyFormVO> queryResult = new QueryResult<>();
        queryResult.setTotal(satisfyFormVOS.getTotal());
        queryResult.setList(satisfyFormVOS.getResult());
        return new QueryResponseResult(CommonCode.SUCCESS,queryResult);
    }

    @Override
    public CommonResponseResult findById(Long formId) {
        SatisfyFormVO satisfyFormVO = leaninSatisfyFormMapper.findById(formId);
        if (satisfyFormVO == null){
            ExceptionCast.cast(SatisfyFormCode.FORM_NOT_EXIST);
        }
        return new CommonResponseResult(CommonCode.SUCCESS,satisfyFormVO);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseResult addDownLoadCount(Long formId) {
        LeaninSatisfyForm leaninSatisfyForm = leaninSatisfyFormMapper.selectByPrimaryKey(formId);
        if (leaninSatisfyForm == null){
            ExceptionCast.cast(SatisfyFormCode.FORM_NOT_EXIST);
        }
        leaninSatisfyForm.setDownloadCount(leaninSatisfyForm.getDownloadCount() + 1);
        leaninSatisfyFormMapper.updateByPrimaryKeySelective(leaninSatisfyForm);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseResult deleteForm(Long formId) {
        LeaninSatisfyForm leaninSatisfyForm = leaninSatisfyFormMapper.selectByPrimaryKey(formId);
        if (leaninSatisfyForm == null){
            ExceptionCast.cast(SatisfyFormCode.FORM_NOT_EXIST);
        }
        leaninSatisfyFormMapper.deleteByPrimaryKey(formId);

        leaninSatisfyFormDeptMapper.deleteByFormId(formId);
        return ResponseResult.SUCCESS();
    }
}
